// pages/myOrder/myOrder.js
import orderApi from '../../service/orderApi'
import { $wuxCountDown } from '../../components/wux/index.js'
const app = getApp()
let codeConfig = app.globalData.codeConfig

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPupFlag: false, // 物流弹窗
    remarkPupFlag: false, // 说明弹窗
    canRefund: false, // 能退款
    loadTips: '上拉加载',
    showPupFlag: false,
    startPage: 1,
    pageSize: 15,
    loading: false,
    data: {
      buyRecordList: []
    },
    optionTalentId: '',
    orderId: '', // 订单号
    myOrderStatus: {
      PAY_SUCC: 3,
      REFUNDING: 5,
      REFUND_SUCC: 6
    },
    orderType: { // 订单类型
      ORDINARY: '0',
      GROUP: '1',
    },
    bindex: 0,
    upAbled: true, // 是否可上拉加载
    btnFlag: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getRecord()
  },
  
  initTimer (list) {
    // console.log(list)
    for (let i in list) {
      if (list[i].orderType === this.data.orderType.GROUP && list[i].assemble.status === '0') {
        list[i].countDownTimer = new $wuxCountDown({
          date: list[i].assemble.expireTime,
          render (date) {
            this.setData({
              [`data.buyRecordList[${i}].assemble.hours`]: this.leadingZeros(date.hours, 2),
              [`data.buyRecordList[${i}].assemble.min`]: this.leadingZeros(date.min, 2),
              [`data.buyRecordList[${i}].assemble.sec`]: this.leadingZeros(date.sec, 2)
            })
          },
          onEnd () {
            console.log('序号为 '+ i + ' 的订单倒计时结束！！')
            this.setData({
              [`data.buyRecordList[${i}].assemble.status`]: '2',
              [`data.buyRecordList[${i}].status`]: '5',
              [`data.buyRecordList[${i}].statusText`]: '退款中',
            })
          }
        })
      }
    }
    return list
  },
  goDetail(e) {
    var item = e.currentTarget.dataset.item
    if (item.orderType === this.data.orderType.GROUP) {
      wx.navigateTo({
        url:'../group/groupDetail?groupId=' + item.assemble.groupId
      })
    }
  },
  // 我的订单
  getRecord() {
    var that = this
    that.setData({
      loading: true,
      loadTips: '加载中...'
    })
    wx.showLoading({
      title: "加载中"
    })
    var params = {
      startPage: that.data.startPage,
      pageSize: that.data.pageSize
    }
    orderApi.recordOrder(params).then(res => {
      wx.stopPullDownRefresh();
      wx.hideLoading()
      that.setData({
        loading: false
      })
      if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        var _data = res.data.data
        for (var i in _data.buyRecordList) {
          if (_data.buyRecordList[i].status == 3) {
            _data.buyRecordList[i].statusText = '付款成功'
          } else if (_data.buyRecordList[i].status == 5) {
            _data.buyRecordList[i].statusText = '退款中'
          } else if (_data.buyRecordList[i].status == 6) {
            _data.buyRecordList[i].statusText = '退款完成'
          } else if (_data.buyRecordList[i].status == 8) {
            _data.buyRecordList[i].statusText = '下单失败'
          }
        }
        // var arr = that.data.data.buyRecordList.concat(_data.buyRecordList)
        that.setData({
          'data.buyRecordList': that.initTimer(_data.buyRecordList)
        })
        
        if (res.data.data.buyRecordList.length < that.data.pageSize) {
          that.setData({
            loadTips: '暂无更多数据',
            upAbled: false
          })
        } else {
          that.setData({
            loadTips: '上拉加载'
          })
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    }).catch(e => {
      wx.stopPullDownRefresh();
      that.setData({
        loading: false
      })
    })
  },

  // 申请退款按钮
  onApplyRefund (e) {
    var canRefund = e.currentTarget.dataset.canrefund
    var orderId = e.currentTarget.dataset.orderid
    var bindex = e.currentTarget.dataset.bindex
    this.setData({
      canRefund,
      orderId,
      bindex
    })
    this.setData({
      remarkPupFlag : true
    })
  },
  // 狠心退款按钮
  onRefund () {
    var that = this
    if (!that.data.btnFlag) {
      return false
    }
    that.setData({
      remarkPupFlag : false,
      btnFlag: false
    })
    wx.showLoading({
      title: "加载中"
    })
    var params = {
      orderId: that.data.orderId
    }
    orderApi.applyRefund(params).then(res => {
      that.setData({
        btnFlag: true
      })
      if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        wx.hideLoading()
        wx.showToast({
          title: '申请退款成功，将于72小时内退款至您的付款账户。',
          icon: 'none'
        })
        var _status = `data.buyRecordList[${that.data.bindex}].status`
        var _statusText = `data.buyRecordList[${that.data.bindex}].statusText`
        that.setData({
          [_status] : 5,
          [_statusText]: '退款中'
        })
        // that.getRecord()
      } else if (res.data.errCode === codeConfig.errCode.USER_GOODS_NO) {
        wx.hideLoading()
        that.setData({
          canRefund: false,
          remarkPupFlag: true
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }).catch(res => {
    })
  },
  // 关闭说明弹窗
  closeRemark () {
    this.setData({
      remarkPupFlag : false
    })
  },
  // 复制订单号
  onCopy (e) {
    var orderId = e.currentTarget.dataset.orderid
    wx.setClipboardData({
      data: orderId
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      startPage: 1,
      pageSize: 15,
      upAbled: true // 是否可上拉加载
    })
    this.getRecord()
  },

/**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    if (!that.data.upAbled) {
      return false
    }
    if (that.data.loading) {
      return false
    }
    that.setData({
      loading: true,
      loadTips: '加载中...',
      startPage: that.data.startPage + 1
    })
    var params = {
      startPage: that.data.startPage,
      pageSize: that.data.pageSize
    }
    orderApi.recordOrder(params).then(res => {
      that.setData({
        loading: false
      })
      if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        var _data = res.data.data
        for (var i in _data.buyRecordList) {
          if (_data.buyRecordList[i].status == 3) {
            _data.buyRecordList[i].statusText = '付款成功'
          } else if (_data.buyRecordList[i].status == 5) {
            _data.buyRecordList[i].statusText = '退款中'
          } else if (_data.buyRecordList[i].status == 6) {
            _data.buyRecordList[i].statusText = '退款完成'
          }
        }
        var arr = that.data.data.buyRecordList.concat(_data.buyRecordList)
        that.setData({
          'data.buyRecordList': that.initTimer(arr)
        })
        if (res.data.data.buyRecordList.length < that.data.pageSize) {
          that.setData({
            loadTips: '暂无更多数据',
            upAbled: false,
            startPage: that.data.startPage - 1
          })
        } else {
          that.setData({
            loadTips: '上拉加载'
          })
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    }).catch(e => {
      console.log(e)
      that.setData({
        loading: false
      })
    })
  },
/**
 * 分享按钮
 */
  onShareAppMessage: function (e) {
    // console.log(e)
    if (e.from === 'button') {
      // 店铺分享
      return {
        path: '/pages/group/groupDetail?groupId=' + e.target.dataset.groupid,
        title: app.globalData.userInfo.nickName + '邀请你参加TA的拼团，全场商品8折任意拼。',
        imageUrl: app.globalData.picBaseUrl + '/group/20190507/CeX4L1XxoTIL.png'
      }
    }
  }
})